# coding:utf-8

import queue
import threading
import time

# python中的Queue模块中提供了同步的、线程安全的队列类，包括：
#   FIFO(先进先出)队列Queue
#   FIFO(后进先出)队列LifoQueue
#   优先级队列PriorityQueue

exitFlag = 0
queueLock = threading.Lock()
workQueue = queue.Queue(10)


def process_data(threadName, q):
    while not exitFlag:
        queueLock.acquire()
        if not workQueue.empty():
            data = q.get()
            queueLock.release()
            print("%s processing %s" % (threadName, data))
        else:
            queueLock.release()
        time.sleep(1)


class myThread(threading.Thread):
    def __init__(self, threadId, name, q):
        threading.Thread.__init__(self)
        self.threadId = threadId
        self.name = name
        self.q = q

    def run(self):
        print("开启线程：" + self.name)
        process_data(self.name, self.q)
        print("退出线程：" + self.name)


threadList = ["Thread-1", "Thread-2", "Thread-3"]
nameList = ["One", "Two", "Three", "Four", "Five"]
threads = []
threadId = 1
for threadName in threadList:
    thread = myThread(threadId, threadName, workQueue)
    thread.start()
    threads.append(thread)
    threadId += 1

# 填充队列
queueLock.acquire()
for word in nameList:
    workQueue.put(word)
queueLock.release()

# 等待队列清空
while not workQueue.empty():
    pass

# 通知线程是时候退出了
exitFlag = 1

for thread in threads:
    thread.join()

print("退出主线程")
